package com.example.foodwebbackend.service;

import com.example.foodwebbackend.dto.MerchantRequest;
import com.example.foodwebbackend.dto.PageRequest;
import com.example.foodwebbackend.dto.PageResponse;
import com.example.foodwebbackend.entity.Merchant;
import com.example.foodwebbackend.mapper.MerchantMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.List;

@Service
public class MerchantService {

    @Autowired
    private MerchantMapper merchantMapper;

    @Autowired
    private PasswordEncoder passwordEncoder;

    /**
     * 商家注册
     */
    public Merchant register(String username, String password, String merchantName, 
                           String merchantAddress, String contactPhone, String businessHours, 
                           String merchantDescription) {
        // 检查用户名是否已存在
        if (merchantMapper.existsByUsername(username)) {
            throw new RuntimeException("用户名已存在");
        }

        // 创建新商家
        Merchant merchant = new Merchant();
        merchant.setUsername(username);
        merchant.setPassword(password);
        merchant.setMerchantName(merchantName);
        merchant.setMerchantAddress(merchantAddress);
        merchant.setContactPhone(contactPhone);
        merchant.setBusinessHours(businessHours != null ? businessHours : "9:00-22:00");
        merchant.setMerchantDescription(merchantDescription);
        merchant.setAvatarPath("/businessmen.png");
        merchant.setCoverImagePath("/businessmen.png");
        merchant.setRegisterTime(LocalDateTime.now());
        merchant.setIsApproved(0); // 待审核

        merchantMapper.insert(merchant);
        return merchant;
    }

    /**
     * 商家登录验证
     */
    public Merchant login(String username, String password) {
        Merchant merchant = merchantMapper.findByUsername(username);
        if (merchant == null) {
            throw new RuntimeException("商家不存在");
        }

        if (!password.equals(merchant.getPassword())) {
            throw new RuntimeException("密码错误");
        }

        if (merchant.getIsApproved() == 0) {
            throw new RuntimeException("商家账号待审核");
        }

        if (merchant.getIsApproved() == 2) {
            throw new RuntimeException("商家账号审核未通过");
        }

        // 更新最后登录时间
        merchantMapper.updateLastLoginTime(merchant.getMerchantId());

        return merchant;
    }

    /**
     * 根据用户名查找商家
     */
    public Merchant findByUsername(String username) {
        return merchantMapper.findByUsername(username);
    }

    /**
     * 根据商家ID查找商家
     */
    public Merchant findById(Integer merchantId) {
        return merchantMapper.findById(merchantId);
    }

    /**
     * 更新商家信息
     */
    public Merchant updateMerchant(Merchant merchant) {
        if (merchant.getPassword() != null && !merchant.getPassword().isEmpty()) {
            merchant.setPassword(merchant.getPassword());
        }
        merchantMapper.update(merchant);
        return merchantMapper.findById(merchant.getMerchantId());
    }

    /**
     * 删除商家
     */
    public void deleteMerchant(Integer merchantId) {
        merchantMapper.deleteById(merchantId);
    }

    /**
     * 获取所有商家
     */
    public List<Merchant> getAllMerchants() {
        return merchantMapper.findAll();
    }

    /**
     * 根据审核状态获取商家
     */
    public List<Merchant> getMerchantsByApprovalStatus(Integer isApproved) {
        return merchantMapper.findByApprovalStatus(isApproved);
    }

    /**
     * 更新审核状态
     */
    public void updateApprovalStatus(Integer merchantId, Integer isApproved) {
        merchantMapper.updateApprovalStatus(merchantId, isApproved);
    }

    /**
     * 检查用户名是否存在
     */
    public boolean existsByUsername(String username) {
        return merchantMapper.existsByUsername(username);
    }

    /**
     * 统计商家总数
     */
    public int countMerchants() {
        return merchantMapper.countMerchants();
    }

    /**
     * 获取评分最高的商家
     */
    public List<Merchant> getTopRatedMerchants(Integer limit) {
        return merchantMapper.findByRatingDesc(limit);
    }

    /**
     * 搜索商家
     */
    public List<Merchant> searchMerchants(String keyword) {
        return merchantMapper.searchMerchants(keyword);
    }

    /**
     * 分页获取商家列表
     */
    public PageResponse<Merchant> getMerchantsWithPagination(PageRequest pageRequest) {
        List<Merchant> merchants = merchantMapper.findMerchantsWithPagination(pageRequest);
        long total = merchantMapper.countMerchantsWithSearch(pageRequest.getSearch(), pageRequest.getApprovalStatus());
        return new PageResponse<>(merchants, pageRequest.getPage(), pageRequest.getSize(), total);
    }

    /**
     * 创建商家
     */
    public Merchant createMerchant(MerchantRequest request) {
        Merchant merchant = new Merchant();
        merchant.setUsername(request.getUsername());
        merchant.setPassword(request.getPassword());
        merchant.setMerchantName(request.getMerchantName());
        merchant.setMerchantAddress(request.getMerchantAddress());
        merchant.setContactPhone(request.getContactPhone());
        merchant.setMerchantDescription(request.getMerchantDescription());
        merchant.setBusinessHours(request.getBusinessHours() != null ? request.getBusinessHours() : "9:00-22:00");
        merchant.setAvatarPath(request.getAvatarPath() != null ? request.getAvatarPath() : "/businessmen.png");
        merchant.setCoverImagePath(request.getCoverImagePath() != null ? request.getCoverImagePath() : "/businessmen.png");
        merchant.setFeatures(request.getFeatures());
        merchant.setRegisterTime(LocalDateTime.now());
        merchant.setIsApproved(request.getIsApproved() != null ? request.getIsApproved() : 0);
        
        merchantMapper.insert(merchant);
        return merchant;
    }

    /**
     * 更新商家
     */
    public Merchant updateMerchant(Integer merchantId, MerchantRequest request) {
        Merchant merchant = merchantMapper.findById(merchantId);
        if (merchant == null) {
            throw new RuntimeException("商家不存在");
        }
        
        if (request.getUsername() != null) {
            merchant.setUsername(request.getUsername());
        }
        if (request.getPassword() != null && !request.getPassword().trim().isEmpty()) {
            merchant.setPassword(request.getPassword());
        }
        if (request.getMerchantName() != null) {
            merchant.setMerchantName(request.getMerchantName());
        }
        if (request.getMerchantAddress() != null) {
            merchant.setMerchantAddress(request.getMerchantAddress());
        }
        if (request.getContactPhone() != null) {
            merchant.setContactPhone(request.getContactPhone());
        }
        if (request.getMerchantDescription() != null) {
            merchant.setMerchantDescription(request.getMerchantDescription());
        }
        if (request.getBusinessHours() != null) {
            merchant.setBusinessHours(request.getBusinessHours());
        }
        if (request.getAvatarPath() != null) {
            merchant.setAvatarPath(request.getAvatarPath());
        }
        if (request.getCoverImagePath() != null) {
            merchant.setCoverImagePath(request.getCoverImagePath());
        }
        if (request.getFeatures() != null) {
            merchant.setFeatures(request.getFeatures());
        }
        if (request.getIsApproved() != null) {
            merchant.setIsApproved(request.getIsApproved());
        }
        
        merchantMapper.update(merchant);
        return merchantMapper.findById(merchantId);
    }

    /**
     * 批量删除商家
     */
    public int batchDeleteMerchants(List<Integer> merchantIds) {
        return merchantMapper.batchDeleteByIds(merchantIds);
    }

    /**
     * 批量更新审核状态
     */
    public int batchUpdateApprovalStatus(List<Integer> merchantIds, Integer isApproved) {
        return merchantMapper.batchUpdateApprovalStatus(merchantIds, isApproved);
    }
} 